package jcu.ict.profaid;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class FormSignIn extends Activity {
	private AlertDialogManager alert;
	private SessionManager session;
	private EditText edtEmail;
	private SignDbAdapter SignIn;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.form_sign_in);

		edtEmail = (EditText) findViewById(R.id.edtSignIn);
		TextView txtSignUp = (TextView) findViewById(R.id.txtSignUp);

		alert = new AlertDialogManager();
		session = new SessionManager(getApplicationContext());
		SignIn = new SignDbAdapter(getBaseContext());

		//Toast.makeText(getApplicationContext(),"User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show();

		if(session.isLoggedIn() == true){
			Intent myIntent = new Intent(FormSignIn.this,
					MainActivity.class);
			startActivity(myIntent);
			finish();
		}
		
		txtSignUp.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent myIntent = new Intent(FormSignIn.this, FormSignUp.class);
				startActivity(myIntent);
			}
		});

		Button btnSignIn = (Button) findViewById(R.id.btnSignIn);
		btnSignIn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				String emailPass = edtEmail.getText().toString();
				try {
					if (emailPass.trim().length() > 0) {
						SignIn.open();
						Cursor xCursor = SignIn.populateSignIn(emailPass);
						xCursor.moveToFirst();

						String login = xCursor.getString(0);

						if (login.length() > 0) {
							Toast.makeText(getBaseContext(), "Login success",
									Toast.LENGTH_LONG).show();
							session.createLoginSession(login, emailPass);
							Intent myIntent = new Intent(FormSignIn.this,
									MainActivity.class);
							startActivity(myIntent);
							finish();
							SignIn.close();
						} else {
							alert.showAlertDialog(FormSignIn.this,
									"Login failed..",
									"Username/Password is incorrect", false);
						}
					} else {
						alert.showAlertDialog(FormSignIn.this,
								"Login failed..",
								"Username/Password is incorrect", false);
					}
				} catch (Exception e) {
					alert.showAlertDialog(FormSignIn.this,
							"Login failed..",
							"Username/Password is incorrect", false);
				}

			}
		});
	}
}
